import React, {useState, useEffect, useRef} from 'react'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faTimes, faEdit, faTrash} from '@fortawesome/free-solid-svg-icons'
import {faMarkdown} from '@fortawesome/free-brands-svg-icons'
import useKeyPress from '../hooks/useKeyPress'

export default ({files, onSaveEdit, onFileDelete, onFileClick}) => {
  const [editStatus, setEditStatus] = useState(false)
  const [value, setValue] = useState('')
  const enterPressed = useKeyPress(13)
  const escPressed = useKeyPress(27)
  const node = useRef(null)

  const closeSearch = (editItem) => {
    setEditStatus(false)
    setValue('')
    editItem.isNew && onFileDelete(editItem.id)
  }

  useEffect(() => {
    editStatus && node.current.focus()
  }, [editStatus])

  useEffect(() => {
    const editItem = files.find(file => file.id === editStatus)
    if (enterPressed && editStatus && value.trim() !== '') {
      onSaveEdit(editItem.id, value, editItem.isNew)
      setEditStatus(false)
      setValue('')
    }

    escPressed && editStatus && closeSearch(editItem)
  })

  useEffect(() => {
    const newFile = files.find(file => file.isNew)
    if (newFile) {
      setEditStatus(newFile.id)
      setValue(newFile.title)
    }
  }, [files])

  return (
    <ul className="list-group list-group-flush file-list">
      {files?.map(file => (
        <li
          className="list-group-item bg-light row d-flex align-items-center file-item mx-0"
          key={file.id}
          data-id={file.id}
          data-title={file.title}
        >
          {(file.id !== editStatus && !file.isNew) &&
          <>
            <span className="col-2">
                <FontAwesomeIcon size="lg" icon={faMarkdown}/>
            </span>
            <span className="col-6 c-link" onClick={() => onFileClick(file.id)}>{file.title}</span>
            <button type="button" className="icon-button col-1" onClick={() => {
              setEditStatus(file.id);
              setValue(file.title);
            }}>
              <FontAwesomeIcon title="编辑" size="lg" icon={faEdit}/>
            </button>
            <button type="button" className="icon-button col-1" onClick={() => onFileDelete(file.id)}>
              <FontAwesomeIcon title="删除" size="lg" icon={faTrash}/>
            </button>
          </>
          }
          {(file.id === editStatus || file.isNew) &&
          <>
            <input className="form-control col-10"
                   value={value} placeholder="请输入文件名称" ref={node}
                   onChange={(e) => setValue(e.target.value)}
            />
            <button type="button" className="icon-button col-2" onClick={() => closeSearch(file)}>
              <FontAwesomeIcon title="关闭" size="lg" icon={faTimes}/>
            </button>
          </>
          }
        </li>
      ))}
    </ul>
  )
}
